package com.zkas.canalefectivo.datasyncro;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;

  
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Database extends SQLiteOpenHelper implements DataStore {

	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 3;

	// Database Name
	private static final String DATABASE_NAME = "CanalEfectivo";

	// Contacts table name
	private static final String TABLE_BILLS = "Bills";

	/*// Contacts Table Columns names
	private static final String KEY_ID = "id";
	private static final String KEY_NAME = "name";
	private static final String KEY_PH_NO = "phone_number";
	*/
	private static final String EMPRESA = "empresa";
	private static final String SERVICIO = "servicio";
	private static final String IDENTIF = "identificador";
	private static final String FECHA1 = "fecha1";
	private static final String MONTO1 = "monto1";
	private static final String FECHA2 = "fecha2";
	private static final String MONTO2 = "monto2";
	private static final String ENTIDAD = "entidad";
	private static final String CONVENIO = "convenio";
	private static final String ESTADO = "estado";			// 'D' en deuda, 'P' pagada, 'C' confirmado el pago. 
	private static final String FECHAPAGO = "fechapago";   	// fecha en que se pago
	
	
	public Database(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	// Creating Tables
	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_BILLS + "(" + 
				EMPRESA + " TEXT," +  
				SERVICIO + " TEXT," +  
				IDENTIF + " TEXT," +  
				FECHA1 + " TEXT," +  
				MONTO1 + " TEXT," +  
				FECHA2 + " TEXT," +  
				MONTO2 + " TEXT," +  
				ENTIDAD + " TEXT," +  
				CONVENIO + " TEXT," +   
				ESTADO + " TEXT, " + 
				FECHAPAGO + " TEXT" + ")";  
		db.execSQL(CREATE_CONTACTS_TABLE);
	}

	// Upgrading database
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Drop older table if existed
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_BILLS);

		// Create tables again
		onCreate(db);
	}

	public void saveBills(ArrayList<HashMap<String, String>> dataIn) {
		// TODO Auto-generated method stub
		// antes de guardar, hay qe sincronizar con los anteriores!
		// por ahora se borra.
		
		SQLiteDatabase db = this.getWritableDatabase();
		onUpgrade(db, 0, 0);
				
		//db.execSQL("DELETE FROM " + TABLE_BILLS);  // no anda...
		String algo="";
		HashMap<String, String> one = null;
		for (int i = 0; i < dataIn.size(); i++) {
			one = dataIn.get(i);
	        addBill(db,new Bill(one));			
		}	
		db.close();	
        // addBill(db,new Bill("EDENOR S.A          Electricidad        6544567890123456789020130510134.00    20130422151.00    45644321"));
        //addBill(db,new Bill("EDESUR S.A.         Electricidad        6784567890123456789020130410325.43    20130420431.45    42344324"));
        
        // Reading all contacts
        Log.d("Factura", "Leyendo de la base");
        List<Bill> bills = getAllBills();
 
        for (Bill cn : bills) 
        {
            String log = "EMPRESA: "+cn.getEmpresa()+" ,Id: " + cn.getIdentif() + " ,Monto1: " + cn.getMonto1();
            // Writing Contacts to log
            Log.d("Factura", log);
        }
		
	}
	/**
	 * All CRUD(Create, Read, Update, Delete) Operations
	 */

	// Adding new contact
	void addBill(SQLiteDatabase db, Bill bill) {
		//SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(EMPRESA, bill.getEmpresa()); // Contact Name
		values.put(SERVICIO, bill.getServicio()); // Contact Name
		values.put(IDENTIF, bill.getIdentif()); // Contact Name
		values.put(FECHA1, bill.getFecha1()); // Contact Name
		values.put(MONTO1, bill.getMonto1()); // Contact Name
		values.put(FECHA2, bill.getFecha2()); // Contact Name
		values.put(MONTO2, bill.getMonto2()); // Contact Name
		values.put(ENTIDAD, bill.getEntidad()); // Contact Name
		values.put(CONVENIO, bill.getConvenio()); // Contact Name
		values.put(ESTADO, bill.getEstado()); // Contact Name
		values.put(FECHAPAGO, bill.getFechaPago()); // Contact Name

		// Inserting Row
		try {
		db.insertOrThrow(TABLE_BILLS, null, values);
		//db.close(); // Closing database connection
		}
		catch (Exception e) {
			e.printStackTrace();
		} 
	}

	// Getting single bill
	/*
	Bill getBill(String identif) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_BILLS, new String[] { KEY_ID,
				KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
				new String[] { String.valueOf(id) }, null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
				cursor.getString(1), cursor.getString(2));
		// return contact
		return contact;
	}
	*/
	
	// Getting All Contacts
	public List<Bill> getAllBills() {
		List<Bill> billList = new ArrayList<Bill>();
		// Select All Query
		String selectQuery = "SELECT * FROM " + TABLE_BILLS; 
				//"EMPRESA, SERVICIO, IDENTIF, FECHA1, MONTO1, FECHA2, MONTO2, ENTIDAD, CONVENIO, ESTADO, FECHAPAGO " + 
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);
		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Bill bill = new Bill();				
				bill.setEmpresa(cursor.getString(0));
				bill.setServicio(cursor.getString(1));
				bill.setIdentif(cursor.getString(2));
				bill.setFecha1(cursor.getString(3));
				bill.setMonto1(cursor.getString(4));
				bill.setFecha2(cursor.getString(5));
				bill.setMonto2(cursor.getString(6));
				bill.setEntidad(cursor.getString(7));
				bill.setConvenio(cursor.getString(8));
				bill.setEstado(cursor.getString(9));
				bill.setFechaPago(cursor.getString(10));
				// Adding bill to list
				billList.add(bill);
			} while (cursor.moveToNext());
		}

		// return contact list
		return billList;
	}

	private String dateNow()
	{
		Date now = new Date();
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddhhmm");
	    return dateFormatter.format(now);		
	}
	
	// Updating single contact
	// ASumo que se usa cuando una bill pasa de a pagar, a pagada. Se pone la fecha del dia.
	public int updateBill(Bill bill) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();

		values.put(FECHAPAGO, dateNow());		
		values.put(ESTADO, "P");			// en realidad hay que poner la fecha del dia.

		// updating row
		return db.update(TABLE_BILLS, values, IDENTIF + " = ?",
				new String[] { String.valueOf(bill.getIdentif()) });
	}

	// Deleting single contact
	public void deleteBill(Bill bill) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_BILLS, IDENTIF + " = ?",
				new String[] { String.valueOf(bill.getIdentif()) });
		db.close();
	}


	// Getting contacts Count
	public int getContactsCount() {
		String countQuery = "SELECT  * FROM " + TABLE_BILLS;
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		cursor.close();

		// return count
		return cursor.getCount();
	}
}
